package com.best.guanfengji

import android.os.Bundle
import android.os.CountDownTimer
import android.os.Handler
import android.os.Looper
import android.os.Message
import android.util.Log
import androidx.appcompat.app.AppCompatActivity
import com.best.guanfengji.serial_port.KTDataUtils
import com.best.guanfengji.serial_port.MyAlertDialog
import com.best.guanfengji.serial_port.SerialPortCommand
import com.best.guanfengji.serial_port.SerialPortManager
import com.blankj.utilcode.util.SPUtils
import com.blankj.utilcode.util.ToastUtils
import kotlinx.android.synthetic.main.activity_main.delete_single_yield
import kotlinx.android.synthetic.main.activity_main.indicator_blow
import kotlinx.android.synthetic.main.activity_main.indicator_canister
import kotlinx.android.synthetic.main.activity_main.indicator_cut_material
import kotlinx.android.synthetic.main.activity_main.indicator_down_blow_insert
import kotlinx.android.synthetic.main.activity_main.indicator_down_clamp
import kotlinx.android.synthetic.main.activity_main.indicator_down_corner_cut
import kotlinx.android.synthetic.main.activity_main.indicator_down_inject_insert
import kotlinx.android.synthetic.main.activity_main.indicator_down_mould
import kotlinx.android.synthetic.main.activity_main.indicator_down_move_material_down
import kotlinx.android.synthetic.main.activity_main.indicator_down_move_material_up
import kotlinx.android.synthetic.main.activity_main.indicator_inject
import kotlinx.android.synthetic.main.activity_main.indicator_left_get_material
import kotlinx.android.synthetic.main.activity_main.indicator_left_move_material
import kotlinx.android.synthetic.main.activity_main.indicator_right_get_material
import kotlinx.android.synthetic.main.activity_main.indicator_right_move_material
import kotlinx.android.synthetic.main.activity_main.indicator_start_welding
import kotlinx.android.synthetic.main.activity_main.indicator_trim
import kotlinx.android.synthetic.main.activity_main.indicator_up_blow_insert
import kotlinx.android.synthetic.main.activity_main.indicator_up_clamp
import kotlinx.android.synthetic.main.activity_main.indicator_up_corner_cut
import kotlinx.android.synthetic.main.activity_main.indicator_up_inject_insert
import kotlinx.android.synthetic.main.activity_main.indicator_up_mould
import kotlinx.android.synthetic.main.activity_main.indicator_up_move_material_down
import kotlinx.android.synthetic.main.activity_main.indicator_up_move_material_up
import kotlinx.android.synthetic.main.activity_main.input_blow
import kotlinx.android.synthetic.main.activity_main.input_canister
import kotlinx.android.synthetic.main.activity_main.input_cut_material
import kotlinx.android.synthetic.main.activity_main.input_inject
import kotlinx.android.synthetic.main.activity_main.input_squeeze_material
import kotlinx.android.synthetic.main.activity_main.input_start_welding
import kotlinx.android.synthetic.main.activity_main.input_trim
import kotlinx.android.synthetic.main.activity_main.iv_capsule_left
import kotlinx.android.synthetic.main.activity_main.iv_capsule_right
import kotlinx.android.synthetic.main.activity_main.tv_blow
import kotlinx.android.synthetic.main.activity_main.tv_blow_insert
import kotlinx.android.synthetic.main.activity_main.tv_canister
import kotlinx.android.synthetic.main.activity_main.tv_clamp
import kotlinx.android.synthetic.main.activity_main.tv_corner_cut
import kotlinx.android.synthetic.main.activity_main.tv_cut_material
import kotlinx.android.synthetic.main.activity_main.tv_get_material
import kotlinx.android.synthetic.main.activity_main.tv_inject
import kotlinx.android.synthetic.main.activity_main.tv_inject_insert
import kotlinx.android.synthetic.main.activity_main.tv_linkage
import kotlinx.android.synthetic.main.activity_main.tv_mould
import kotlinx.android.synthetic.main.activity_main.tv_move_material
import kotlinx.android.synthetic.main.activity_main.tv_move_material_down
import kotlinx.android.synthetic.main.activity_main.tv_move_material_up
import kotlinx.android.synthetic.main.activity_main.tv_produce_all
import kotlinx.android.synthetic.main.activity_main.tv_produce_capsule
import kotlinx.android.synthetic.main.activity_main.tv_progress1
import kotlinx.android.synthetic.main.activity_main.tv_progress2
import kotlinx.android.synthetic.main.activity_main.tv_progress3
import kotlinx.android.synthetic.main.activity_main.tv_progress4
import kotlinx.android.synthetic.main.activity_main.tv_progress5
import kotlinx.android.synthetic.main.activity_main.tv_progress6
import kotlinx.android.synthetic.main.activity_main.tv_progress7
import kotlinx.android.synthetic.main.activity_main.tv_progress8
import kotlinx.android.synthetic.main.activity_main.tv_single_yield
import kotlinx.android.synthetic.main.activity_main.tv_squeeze_material
import kotlinx.android.synthetic.main.activity_main.tv_start_welding
import kotlinx.android.synthetic.main.activity_main.tv_total_yield
import kotlinx.android.synthetic.main.activity_main.tv_trim
import java.math.BigDecimal

class MainActivity : AppCompatActivity(), SerialPortManager.OnSerialPortDataListener {

    var paramsTrim = SPUtils.getInstance().getString("paramsTrim")
    var paramsStartWelding = SPUtils.getInstance().getString("paramsStartWelding")
    var paramsInject = SPUtils.getInstance().getString("paramsInject")
    var paramsBlow = SPUtils.getInstance().getString("paramsBlow")
    var paramsCanister = SPUtils.getInstance().getString("paramsCanister")
    var paramsCutMaterial = SPUtils.getInstance().getString("paramsCutMaterial")
    var paramSqueezeMaterial = SPUtils.getInstance().getString("paramSqueezeMaterial")

    var x1 = false
    var x2 = false
    var x3 = false
    var x4 = false
    var x5 = false
    var x6 = false
    var x7 = false
    var x8 = false
    var x9 = false
    var x10 = false
    var x11 = false
    var x12 = false
    var x15 = false
    var x16 = false
    var x17 = false
    var x18 = false
    var x19 = false
    var x21 = false
    var x22 = false

    var sealCapsuleCount = 0
    var cutCapsuleCount = 0

    var materialStatus = 1


    var isEmergencyStop = false

    var isAutoProducing = false

    private val cutMaterialInterval = 200L

//    private val injectConstant = 0.8
//    private val pinglv = 12000
    private val pulseConversionCoefficient = 0.8
    private val injectTimeMill = 7000L

    private var initXTime = 0

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        SerialPortManager.instance.addOnSerialPortDataListener(this)

        setContentView(R.layout.activity_main)

        // 隐藏导航栏
//        val decorView = window.decorView
//        val uiOptions = View.SYSTEM_UI_FLAG_HIDE_NAVIGATION or View.SYSTEM_UI_FLAG_IMMERSIVE_STICKY
//        decorView.systemUiVisibility = uiOptions

        input_trim.text = paramsTrim
        input_start_welding.text = paramsStartWelding
        input_inject.text = paramsInject
        input_blow.text = paramsBlow
        input_canister.text = paramsCanister
        input_cut_material.text = paramsCutMaterial
        input_squeeze_material.text = paramSqueezeMaterial

        input_trim.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_trim.text = text
                    SPUtils.getInstance().put("paramsTrim",text)
                    paramsTrim = text
                }
            }).show(supportFragmentManager,null)
        }
        input_start_welding.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_start_welding.text = text
                    SPUtils.getInstance().put("paramsStartWelding",text)
                    paramsStartWelding = text
                }
            }).show(supportFragmentManager,null)
        }
        input_inject.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_inject.text = text
                    SPUtils.getInstance().put("paramsInject",text)
                    paramsInject = text
                }
            }).show(supportFragmentManager,null)
        }
        input_blow.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_blow.text = text
                    SPUtils.getInstance().put("paramsBlow",text)
                    paramsBlow = text
                }
            }).show(supportFragmentManager,null)
        }
        input_canister.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_canister.text = text
                    SPUtils.getInstance().put("paramsCanister",text)
                    paramsCanister = text
                }
            }).show(supportFragmentManager,null)
        }
        input_cut_material.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_cut_material.text = text
                    SPUtils.getInstance().put("paramsCutMaterial",text)
                    paramsCutMaterial = text
                }
            }).show(supportFragmentManager,null)
        }
        input_squeeze_material.setOnClickListener {
            MyInputDialog(object :MyInputDialog.OnInputClickListener{
                override fun onSubmitClick(text: String) {
                    input_squeeze_material.text = text
                    SPUtils.getInstance().put("paramSqueezeMaterial",text)
                    paramSqueezeMaterial = text
                }
            }).show(supportFragmentManager,null)
        }


        tv_move_material_up.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY14(if(b) 1 else 0))
        }
        tv_move_material_down.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY13(if(b) 1 else 0))
        }
        tv_trim.setOnClickListener {
            if(paramsTrim.isNullOrEmpty()){
                ToastUtils.showShort("焊后修剪时间不能为空")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY10(1))

            val countDownTimer = object :CountDownTimer((paramsTrim.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_trim.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY10(0))
                    runOnUiThread {
                        tv_trim.isEnabled = true
                        input_trim.text = paramsTrim
                    }
                }
            }
            countDownTimer.start()
            tv_trim.isEnabled = false
        }
        tv_start_welding.setOnClickListener {
            if(paramsStartWelding.isNullOrEmpty()){
                ToastUtils.showShort("焊接启动时间不能为空")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY17(1))
            indicator_start_welding.setImageResource(R.drawable.ic_indicator_green)

            val countDownTimer = object :CountDownTimer((paramsStartWelding.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_start_welding.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY17(0))
                    runOnUiThread {
                        indicator_start_welding.setImageResource(R.drawable.ic_indicator_red)
                        tv_start_welding.isEnabled = true
                        input_start_welding.text = paramsTrim
                    }
                }
            }
            countDownTimer.start()
            tv_start_welding.isEnabled = false
        }
        tv_clamp.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY9(if(b) 1 else 0))
        }
        tv_inject.setOnClickListener {
            if(paramsInject.isNullOrEmpty()){
                ToastUtils.showShort("定量注液时间不能为空")
                return@setOnClickListener
            }
//            val pulse = (paramsInject.toFloat() * pinglv * injectConstant).toInt()
            val pulse = paramsInject.toInt()
            if(pulse>65535){
                ToastUtils.showShort("定量注液时间超出最大可设置值")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.injectSolution(KTDataUtils.intToHex(pulse,2),"01"))
            indicator_inject.setImageResource(R.drawable.ic_indicator_green)

//            val time = BigDecimal(paramsInject).divide(BigDecimal(injectConstant),1,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal(1000))
//            val time = BigDecimal(paramsInject).divide(BigDecimal(pulseConversionCoefficient),1,BigDecimal.ROUND_HALF_UP)
            val countDownTimer = object :CountDownTimer(injectTimeMill,1000L){
                override fun onTick(p0: Long) {
//                    var sec = BigDecimal(p0).divide(BigDecimal(1000),1,BigDecimal.ROUND_HALF_UP)
                    runOnUiThread {
                        input_inject.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    runOnUiThread {
                        indicator_inject.setImageResource(R.drawable.ic_indicator_red)
                        tv_inject.isEnabled = true
                        input_inject.text = paramsInject
                    }
                }
            }
            countDownTimer.start()
            tv_inject.isEnabled = false
        }
        tv_inject_insert.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY8(if(b) 1 else 0))
        }
        tv_corner_cut.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY7(if(b) 1 else 0))
        }
        tv_blow.setOnClickListener {
            if(paramsBlow.isNullOrEmpty()){
                ToastUtils.showShort("吹气定型时间不能为空")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY6(1))
            indicator_blow.setImageResource(R.drawable.ic_indicator_green)

            val countDownTimer = object :CountDownTimer((paramsBlow.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_blow.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY6(0))
                    runOnUiThread {
                        indicator_blow.setImageResource(R.drawable.ic_indicator_red)
                        tv_blow.isEnabled = true
                        input_blow.text = paramsBlow
                    }
                }
            }
            countDownTimer.start()
            tv_blow.isEnabled = false
        }
        tv_blow_insert.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY5(if(b) 1 else 0))
        }
        tv_mould.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY4(if(b) 1 else 0))
        }
        tv_canister.setOnClickListener {
            if(paramsCanister.isNullOrEmpty()){
                ToastUtils.showShort("料筒升起时间不能为空")
                return@setOnClickListener
            }
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(1))
            indicator_canister.setImageResource(R.drawable.ic_indicator_green)

            val countDownTimer = object :CountDownTimer((paramsCanister.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_canister.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(0))
                    runOnUiThread {
                        indicator_canister.setImageResource(R.drawable.ic_indicator_red)
                        tv_canister.isEnabled = true
                        input_canister.text = paramsCanister
                    }
                }
            }
            countDownTimer.start()
            tv_canister.isEnabled = false
        }
        tv_linkage.setOnClickListener {
            if(paramsCanister.isNullOrEmpty()){
                ToastUtils.showShort("料筒升起时间不能为空")
                return@setOnClickListener
            }
            if(paramsCutMaterial.isNullOrEmpty()){
                ToastUtils.showShort("原料热切时间不能为空")
                return@setOnClickListener
            }

            indicator_cut_material.setImageResource(R.drawable.ic_indicator_green)
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(1))
            val timerCutMaterial = object :CountDownTimer((paramsCutMaterial.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_cut_material.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(0))
                    runOnUiThread {
                        indicator_cut_material.setImageResource(R.drawable.ic_indicator_red)
                        tv_cut_material.isEnabled = true
                        input_cut_material.text = paramsCutMaterial
                    }
                }
            }
            timerCutMaterial.start()
            tv_cut_material.isEnabled = false
            tv_canister.isEnabled = false

            autoProduceHandler.sendEmptyMessageDelayed(messageCanisterWork,cutMaterialInterval)
        }
        tv_cut_material.setOnClickListener {
            if(paramsCutMaterial.isNullOrEmpty()){
                ToastUtils.showShort("原料热切时间不能为空")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(1))
            indicator_cut_material.setImageResource(R.drawable.ic_indicator_green)

            val countDownTimer = object :CountDownTimer((paramsCutMaterial.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_cut_material.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(0))
                    runOnUiThread {
                        indicator_cut_material.setImageResource(R.drawable.ic_indicator_red)
                        tv_cut_material.isEnabled = true
                        input_cut_material.text = paramsCutMaterial
                    }
                }
            }
            countDownTimer.start()
            tv_cut_material.isEnabled = false
        }
        tv_move_material.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY12(if(b) 1 else 0))
        }
        tv_get_material.setOnCheckedChangeListener { _, b ->
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY3(if(b) 1 else 0))
        }
        tv_squeeze_material.setOnClickListener {
            if(paramSqueezeMaterial.isNullOrEmpty()){
                ToastUtils.showShort("原料挤出时间不能为空")
                return@setOnClickListener
            }

            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY16(1))

            val countDownTimer = object :CountDownTimer((paramSqueezeMaterial.toFloat()*1000L).toLong(),1000L){
                override fun onTick(p0: Long) {
                    runOnUiThread {
                        input_squeeze_material.text = (p0/1000).toString()
                    }
                }

                override fun onFinish() {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY16(0))
                    runOnUiThread {
                        tv_squeeze_material.isEnabled = true
                        input_squeeze_material.text = paramSqueezeMaterial
                    }
                }
            }
            countDownTimer.start()
            tv_squeeze_material.isEnabled = false
        }

        tv_produce_all.setOnCheckedChangeListener { compoundButton, b ->
            if(b){
                startAllAutoProduce()
            }else{
                stopAllAutoProduce()
            }
        }

        delete_single_yield.setOnClickListener {
            MyAlertDialog("是否确认清除单次生产量",object :MyAlertDialog.OnAlertClickListener{
                override fun onRightClick() {
                    tv_single_yield.text = "单次生产量：0"
                    SPUtils.getInstance().remove("singleProduceNumber")
                }
            }).show(supportFragmentManager,null)
        }
        var showTag = 1
        tv_total_yield.setOnLongClickListener {
            if(showTag==1){
                showTag = 2
                tv_total_yield.text = "胶囊生产/灌封一体机"
            }else{
                showTag = 1
                tv_total_yield.text = "历史总产量：${SPUtils.getInstance().getInt("totalProduceNumber",0)}"
            }
            true
        }

        tv_total_yield.text = "历史总产量：${SPUtils.getInstance().getInt("totalProduceNumber",0)}"
        tv_single_yield.text = "单次生产量：${SPUtils.getInstance().getInt("singleProduceNumber",0)}"

        SerialPortManager.instance.sendStringData(SerialPortCommand.getXState())
    }

    private fun startAllAutoProduce(){
        if(paramsTrim.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("焊后修剪时间不能为空")
            return
        }
        if(paramSqueezeMaterial.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("原料挤出时间不能为空")
            return
        }
        if(paramsCanister.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("料筒升起时间不能为空")
            return
        }
        if(paramsCutMaterial.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("原料热切时间不能为空")
            return
        }
        if(paramsBlow.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("吹气定型时间不能为空")
            return
        }
        if(paramsStartWelding.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("焊接启动时间不能为空")
            return
        }
        if(paramsInject.isNullOrEmpty()){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("定量注液时间不能为空")
            return
        }
        if(isEmergencyStop){
            setAutoProduceBtnChecked(false)
            ToastUtils.showShort("请解除急停状态后再开始生产")
            return
        }
        if(checkXState()){
            initXTime = 0
            isAutoProducing = true
            setOperationEnable(false)
            squeezeMaterial()
            autoProduceHandler.sendEmptyMessageDelayed(messageStartMoveStep,(paramSqueezeMaterial.toFloat()*1000L).toLong())
        }else{
            if(initXTime>3){
                setAutoProduceBtnChecked(false)
                ToastUtils.showLong("自动复位失败，请手动复位后再开启生产")
                return
            }
            initXTime++
            autoProduceHandler.sendEmptyMessageDelayed(messageInitXPosition,1000)
        }
    }

    private fun stopAllAutoProduce(){
        tv_produce_all.isEnabled = false
        isAutoProducing = false
        setOperationEnable(true)
    }

    private fun setOperationEnable(isEnable:Boolean){
        tv_move_material_up.isEnabled = isEnable
        tv_move_material_down.isEnabled = isEnable
        tv_trim.isEnabled = isEnable
        input_trim.isEnabled = isEnable
        tv_start_welding.isEnabled = isEnable
        input_start_welding.isEnabled = isEnable
        tv_start_welding.isEnabled = isEnable
        tv_clamp.isEnabled = isEnable
        tv_inject.isEnabled = isEnable
        input_inject.isEnabled = isEnable
        tv_inject_insert.isEnabled = isEnable
        tv_corner_cut.isEnabled = isEnable
        tv_blow.isEnabled = isEnable
        input_blow.isEnabled = isEnable
        tv_blow_insert.isEnabled = isEnable
        tv_mould.isEnabled = isEnable
        tv_canister.isEnabled = isEnable
        input_canister.isEnabled = isEnable
        tv_linkage.isEnabled = isEnable
        tv_cut_material.isEnabled = isEnable
        input_cut_material.isEnabled = isEnable
        tv_move_material.isEnabled = isEnable
        tv_get_material.isEnabled = isEnable
        tv_squeeze_material.isEnabled = isEnable
    }

    private fun checkXState():Boolean{
        var isCheckPassed = true
        if(!x21){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY14(1))
            isCheckPassed = false
        }
        if(!x18){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY13(0))
            isCheckPassed = false
        }
        if(!x11){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY9(0))
            isCheckPassed = false
        }
        if(!x10){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY8(0))
            isCheckPassed = false
        }
        if(!x8){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY7(0))
            isCheckPassed = false
        }
        if(!x6){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY5(0))
            isCheckPassed = false
        }
        if(!x4){
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY4(0))
            isCheckPassed = false
        }
        if(!x16){
            isCheckPassed = false
            if(x18){
                SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY12(0))
            }
        }
        if(!x2){
            isCheckPassed = false
            if(x8 && x6){
                SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY3(0))
            }
        }
        return isCheckPassed
    }


    /*-------------------------------------吹塑流程-------------------------------------------*/
    /**
     * A1-挤料
     */
    private fun squeezeMaterial(){
        runOnUiThread {
            tv_progress8.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY16(1))

        val countDownTimer = object :CountDownTimer((paramSqueezeMaterial.toFloat()*1000L).toLong(),1000L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY16(0))
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress8.setBackgroundResource(R.drawable.bg_step_finish)
                }
                SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY16(0))
                materialStatus = 2


//                if(x4 && x2){
//                    takeMaterial()
//                }
            }
        }
        countDownTimer.start()
    }

    /**
     * B1-取料
     */
    private fun takeMaterial(){
        runOnUiThread {
            tv_progress2.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY3(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x1){
                    moldClosing()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress2.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("取料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * B1-合模
     */
    private fun moldClosing(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY4(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x3){
                    extractNeedle()
                    cutMaterial()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress2.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("合模异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * B1-切料
     */
    private fun cutMaterial(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(1))
        autoProduceHandler.sendEmptyMessageDelayed(messageCutMaterial,(paramsCutMaterial.toFloat()*1000).toLong())
        autoProduceHandler.sendEmptyMessageDelayed(messageCanisterWorkAuto1,cutMaterialInterval)
    }

    /**
     * 收料
     */
    private fun backMaterial(){
        materialStatus--
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY3(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x2){
                    runOnUiThread {
                        tv_progress2.setBackgroundResource(R.drawable.bg_step_finish)
                    }

                    if(isAutoProducing){
                        squeezeMaterial()
                    }

                    insertNeedle()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress2.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("收料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * A2-插针
     */
    private fun insertNeedle(){
        runOnUiThread {
            tv_progress7.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY5(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x5){
                    blowAir()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress7.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("插针异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 拔针
     */
    private fun extractNeedle(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY5(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x6){
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("拔针异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * A2-吹气
     */
    private fun blowAir(){
        runOnUiThread {
            tv_progress7.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY6(1))
        autoProduceHandler.sendEmptyMessageDelayed(messageWaitMoveCylinder,(paramsBlow.toFloat()*1000L).toLong())

        autoProduceHandler.sendEmptyMessageDelayed(messageCornerCutDelayed,((paramsBlow.toFloat()-2)*1000L).toLong())
    }

    /**
     * 开模
     */
    private fun moldOpening(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY4(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x4){
                    if(isAutoProducing){
                        takeMaterial()
                    }else{
                        if(materialStatus>0){
                            takeMaterial()
                        }else{
                            tv_produce_all.isEnabled = true
                            extractNeedle()
                        }
                    }
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress2.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("开模异常")
            }
        }
        countDownTimer.start()
    }


    /*-------------------------------------灌封流程-------------------------------------------*/
    /**
     * 移料气缸取料
     */
    private fun moveTakeMaterial(){
        runOnUiThread {
            tv_progress1.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY12(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x15 && x2){
                    moveForwardDown()
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("移料气缸取料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 移料气缸抓下
     */
    private fun moveForwardDown(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY13(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x17){
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("移料抓下夹料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 移料气缸松上
     */
    private fun moveBackwardUp(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY14(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x22 && x4){
                    moveBackMaterial()
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("移料抓上松料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 移料气缸收料
     */
    private fun moveBackMaterial(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY12(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x16){
                    runOnUiThread {
                        tv_progress1.setBackgroundResource(R.drawable.bg_step_finish)
                    }

                    moveForwardUp()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress1.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("移料气缸收料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 移料气缸抓上
     */
    private fun moveForwardUp(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY14(1))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x21){
                    encapsulation()
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("移料抓上夹料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 移料气缸松下
     */
    private fun moveBackwardDown(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY13(0))
        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x18){
//                    if(isAutoProducing){
//                        moveTakeMaterial()
//                    }else{
//                        if(sealCapsuleCount>0 || cutCapsuleCount>0 || materialStatus>0){
//                            moveTakeMaterial()
//                        }
//                    }

                    if(sealCapsuleCount>0 || cutCapsuleCount>0 || materialStatus>0){
                        moveTakeMaterial()
                    }
                    cancel()
                }
            }

            override fun onFinish() {
                errorStop("移料抓下松料异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 灌封流程
     */
    private fun encapsulation(){
        var encapsulationWorkTime = 500L

        if(tv_produce_capsule.isChecked && x19){
//            encapsulationWorkTime = BigDecimal(paramsInject).divide(BigDecimal(injectConstant),1,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal(1000)).toLong()
//            encapsulationWorkTime = BigDecimal(paramsInject).divide(BigDecimal(pulseConversionCoefficient),1,BigDecimal.ROUND_HALF_UP).toLong()
            encapsulationWorkTime = injectTimeMill
            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY8(1))
            val countDownTimer = object :CountDownTimer(10*1000L,500L){
                override fun onTick(p0: Long) {
                    if(isEmergencyStop){
                        cancel()
                        return
                    }

                    if(x9){
                        injectingLiquid()
                        cancel()
                    }
                }

                override fun onFinish() {
                    MyAlertDialog("注液插入异常",object :MyAlertDialog.OnAlertClickListener{
                        override fun onRightClick() {

                        }
                    }).show(supportFragmentManager,null)
                }
            }
            countDownTimer.start()
        }

        if(sealCapsuleCount>0){
            if((paramsStartWelding.toFloat()*1000L).toLong() > encapsulationWorkTime){
                encapsulationWorkTime = (paramsStartWelding.toFloat()*1000L).toLong()
            }
            sealCapsule1()
        }

        if(cutCapsuleCount>0){
            if((paramsTrim.toFloat()*1000L).toLong() > encapsulationWorkTime){
                encapsulationWorkTime = (paramsTrim.toFloat()*1000L).toLong()
            }
            cutCapsule()
        }

        autoProduceHandler.sendEmptyMessageDelayed(messageFinishEncapsulation,encapsulationWorkTime+1500)
    }

    /**
     * 注液
     */
    private fun injectingLiquid(){
        runOnUiThread {
            tv_progress5.setBackgroundResource(R.drawable.bg_step_working)
        }
//        val pulse = (paramsInject.toFloat() * pinglv * injectConstant).toInt()
        val pulse = paramsInject.toInt()
        SerialPortManager.instance.sendStringData(SerialPortCommand.injectSolution(KTDataUtils.intToHex(pulse,2),"01"))

//        val time = BigDecimal(paramsInject).divide(BigDecimal(injectConstant),1,BigDecimal.ROUND_HALF_UP).multiply(BigDecimal(1000))
//        val time = BigDecimal(paramsInject).divide(BigDecimal(pulseConversionCoefficient),1,BigDecimal.ROUND_HALF_UP)
        autoProduceHandler.sendEmptyMessageDelayed(messageInjectingLiquid,injectTimeMill)
    }

    /**
     * 胶囊封口1
     */
    private fun sealCapsule1(){
        runOnUiThread {
            tv_progress4.setBackgroundResource(R.drawable.bg_step_working)
        }

        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY9(1))

        val countDownTimer = object :CountDownTimer(10*1000L,500L){
            override fun onTick(p0: Long) {
                if(isEmergencyStop){
                    cancel()
                    return
                }

                if(x12){
                    sealCapsule2()
                    cancel()
                }
            }

            override fun onFinish() {
                runOnUiThread {
                    tv_progress4.setBackgroundResource(R.drawable.bg_step_error)
                }
                errorStop("焊接夹紧异常")
            }
        }
        countDownTimer.start()
    }

    /**
     * 胶囊封口2
     */
    private fun sealCapsule2(){
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY17(1))
        autoProduceHandler.sendEmptyMessageDelayed(messageSealCapsule,(paramsStartWelding.toFloat()*1000L).toLong())
    }

    /**
     * 焊后修剪
     */
    private fun cutCapsule(){
        runOnUiThread {
            tv_progress3.setBackgroundResource(R.drawable.bg_step_working)
        }
        SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY10(1))
        autoProduceHandler.sendEmptyMessageDelayed(messageCutCapsule,(paramsTrim.toFloat()*1000L).toLong())
    }


    private val messageCanisterWork = 0x001
    private val messageWaitMoveCylinder = 0x002
    private val messageCutMaterial = 0x004
    private val messageCanisterWorkAuto1 = 0x005
    private val messageCanisterWorkAuto2 = 0x006
    private val messageInjectingLiquid = 0x007
    private val messageSealCapsule = 0x008
    private val messageCutCapsule = 0x009
    private val messageStartMoveStep = 0x010
    private val messageFinishEncapsulation = 0x011
    private val messageCornerCut = 0x012
    private val messageInitXPosition = 0x013
    private val messageCornerCutDelayed = 0x014
    private val messageInjectingDelayed = 0x015

    private val autoProduceHandler = object :Handler(Looper.getMainLooper()){
        override fun handleMessage(msg: Message) {
            super.handleMessage(msg)
            when(msg.what){
                messageCanisterWork -> {
                    indicator_canister.setImageResource(R.drawable.ic_indicator_green)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(1))
                    val countDownTimer = object :CountDownTimer((paramsCanister.toFloat()*1000L).toLong(),1000L){
                        override fun onTick(p0: Long) {
                            runOnUiThread {
                                input_canister.text = (p0/1000).toString()
                            }
                        }

                        override fun onFinish() {
                            SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(0))
                            runOnUiThread {
                                indicator_canister.setImageResource(R.drawable.ic_indicator_red)
                                tv_canister.isEnabled = true
                                input_canister.text = paramsCanister
                            }
                        }
                    }
                    countDownTimer.start()
                }
                messageWaitMoveCylinder -> {
                    tv_progress7.setBackgroundResource(R.drawable.bg_step_finish)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY6(0))
                    if(x17 && x15){
                        moveBackwardUp()
                        moldOpening()
                    }else{
                        sendEmptyMessageDelayed(messageWaitMoveCylinder,1000)
                    }
                }
                messageCutMaterial -> {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY2(0))
                    backMaterial()
                }
                messageCanisterWorkAuto1 -> {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(1))
                    sendEmptyMessageDelayed(messageCanisterWorkAuto2,(paramsCanister.toFloat()*1000L).toLong())
                }
                messageCanisterWorkAuto2 -> {
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY1(0))
                }
                messageInjectingLiquid -> {
//                    SerialPortManager.instance.sendStringData(SerialPortCommand.injectSolution(KTDataUtils.intToHex(500,2),"02"))
                    sendEmptyMessageDelayed(messageInjectingDelayed,500)
                }
                messageInjectingDelayed -> {
                    tv_progress5.setBackgroundResource(R.drawable.bg_step_finish)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY8(0))
                    sealCapsuleCount++
                }
                messageSealCapsule -> {
                    tv_progress4.setBackgroundResource(R.drawable.bg_step_finish)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY17(0))
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY9(0))
                    sealCapsuleCount--
                    cutCapsuleCount++
                }
                messageCutCapsule -> {
                    tv_progress3.setBackgroundResource(R.drawable.bg_step_finish)

                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY10(0))
                    cutCapsuleCount--


                    var singleProduceNumber = SPUtils.getInstance().getInt("singleProduceNumber",0)
                    SPUtils.getInstance().put("singleProduceNumber",singleProduceNumber+1)
                    tv_single_yield.text = "单次生产量：${singleProduceNumber+1}"

                    var totalProduceNumber = SPUtils.getInstance().getInt("totalProduceNumber",0)
                    SPUtils.getInstance().put("totalProduceNumber",totalProduceNumber+1)
                    tv_total_yield.text = "历史总产量：${totalProduceNumber+1}"
                }
                messageStartMoveStep -> {
                    moveTakeMaterial()
                    takeMaterial()
                }
                messageFinishEncapsulation -> {
                    moveBackwardDown()
                }
                messageCornerCut -> {
                    tv_progress6.setBackgroundResource(R.drawable.bg_step_finish)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY7(0))
                }
                messageInitXPosition -> {
                    startAllAutoProduce()
                }
                messageCornerCutDelayed -> {
                    tv_progress6.setBackgroundResource(R.drawable.bg_step_working)
                    SerialPortManager.instance.sendStringData(SerialPortCommand.mainCMD.executeY7(1))
                    sendEmptyMessageDelayed(messageCornerCut,800L)
                }
            }
        }
    }


    override fun onDataReceived(text: String) {
        Log.d("TAG", "onDataReceived: :$text")
        val array = text.split(" ")
        if (array[0] == "7E" && array[1] == "7E" && array[2] == "10") {
//            SerialPortManager.instance.sendStringData(SerialPortCommand.feedback(array[3]))
            when (array[3]) {
                "26" -> {//x1-x7
                    if(array[4] == "01"){//x1
                        x1 = true
                        runOnUiThread {
                            indicator_right_get_material.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x1 = false
                        runOnUiThread {
                            indicator_right_get_material.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[5] == "01"){//x2
                        x2 = true
                        runOnUiThread {
                            indicator_left_get_material.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x2 = false
                        runOnUiThread {
                            indicator_left_get_material.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[6] == "01"){//x3
                        x3 = true
                        runOnUiThread {
                            indicator_down_mould.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x3 = false
                        runOnUiThread {
                            indicator_down_mould.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[7] == "01"){//x4
                        x4 = true
                        runOnUiThread {
                            indicator_up_mould.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x4 = false
                        runOnUiThread {
                            indicator_up_mould.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[8] == "01"){//x5
                        x5 = true
                        runOnUiThread {
                            indicator_down_blow_insert.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x5 = false
                        runOnUiThread {
                            indicator_down_blow_insert.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[9] == "01"){//x6
                        x6 = true
                        runOnUiThread {
                            if(!isAutoProducing){
                                tv_get_material.isEnabled = false
                            }
                            indicator_up_blow_insert.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x6 = false
                        runOnUiThread {
                            if(!isAutoProducing){
                                if(x7){
                                    tv_get_material.isEnabled = true
                                }
                            }
                            indicator_up_blow_insert.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[10] == "01"){//x7
                        x7 = true
                        runOnUiThread {
                            if(!isAutoProducing){
                                tv_get_material.isEnabled = false
                            }
                            indicator_down_corner_cut.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x7 = false
                        runOnUiThread {
                            if(!isAutoProducing){
                                if(x6){
                                    tv_get_material.isEnabled = true
                                }
                            }
                            indicator_down_corner_cut.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                }
                "27" -> {//x8-x14
                    if(array[4] == "01"){//x8
                        x8 = true
                        runOnUiThread {
                            indicator_up_corner_cut.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x8 = false
                        runOnUiThread {
                            indicator_up_corner_cut.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[5] == "01"){//x9
                        x9 = true
                        runOnUiThread {
                            indicator_down_inject_insert.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x9 = false
                        runOnUiThread {
                            indicator_down_inject_insert.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[6] == "01"){//x10
                        x10 = true
                        runOnUiThread {
                            indicator_up_inject_insert.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x10 = false
                        runOnUiThread {
                            indicator_up_inject_insert.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[7] == "01"){//x11
                        x11 = true
                        runOnUiThread {
                            indicator_down_clamp.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x11 = false
                        runOnUiThread {
                            indicator_down_clamp.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[8] == "01"){//x12
                        x12 = true
                        runOnUiThread {
                            indicator_up_clamp.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x12 = false
                        runOnUiThread {
                            indicator_up_clamp.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                    if(array[9] == "01"){//x13
                        runOnUiThread {
                            indicator_trim.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        runOnUiThread {
                            indicator_trim.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }
                }
                "28" -> {//x15-x21
                    if(array[4] == "01"){//x15
                        x15 = true
                        runOnUiThread {
                            indicator_right_move_material.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x15 = false
                        runOnUiThread {
                            indicator_right_move_material.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[5] == "01"){//x16
                        x16 = true
                        runOnUiThread {
                            indicator_left_move_material.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x16 = false
                        runOnUiThread {
                            indicator_left_move_material.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[6] == "01"){//x17
                        x17 = true
                        runOnUiThread {
                            indicator_up_move_material_down.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x17 = false
                        runOnUiThread {
                            indicator_up_move_material_down.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[7] == "01"){//x18
                        x18 = true
                        runOnUiThread {
                            indicator_down_move_material_down.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x18 = false
                        runOnUiThread {
                            indicator_down_move_material_down.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[8] == "01"){//x19
                        x19 = true
                        runOnUiThread {
                            iv_capsule_left.setImageResource(R.drawable.bg_capsule_left_on)
                        }
                    }else{
                        x19 = false
                        runOnUiThread {
                            iv_capsule_left.setImageResource(R.drawable.bg_capsule_left_off)
                        }
                    }

                    if(array[9] == "01"){//x20
                        runOnUiThread {
                            iv_capsule_right.setImageResource(R.drawable.bg_capsule_right_on)
                        }
                    }else{
                        runOnUiThread {
                            iv_capsule_right.setImageResource(R.drawable.bg_capsule_right_off)
                        }
                    }

                    if(array[10] == "01"){//x21
                        x21 = true
                        runOnUiThread {
                            indicator_up_move_material_up.setImageResource(R.drawable.ic_indicator_red)
                        }
                    }else{
                        x21 = false
                        runOnUiThread {
                            indicator_up_move_material_up.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                }
                "29" -> {//x22-x23
                    if(array[4] == "01"){//x22
                        x22 = true
                        runOnUiThread {
                            indicator_down_move_material_up.setImageResource(R.drawable.ic_indicator_green)
                        }
                    }else{
                        x22 = false
                        runOnUiThread {
                            indicator_down_move_material_up.setImageResource(R.drawable.ic_indicator_grey)
                        }
                    }

                    if(array[5] == "00"){//x23
                        isEmergencyStop = true
                        autoProduceHandler.removeMessages(messageCanisterWork)
                        autoProduceHandler.removeMessages(messageWaitMoveCylinder)
                        autoProduceHandler.removeMessages(messageCutMaterial)
                        autoProduceHandler.removeMessages(messageCanisterWorkAuto1)
                        autoProduceHandler.removeMessages(messageCanisterWorkAuto2)
                        autoProduceHandler.removeMessages(messageInjectingLiquid)
                        autoProduceHandler.removeMessages(messageSealCapsule)
                        autoProduceHandler.removeMessages(messageCutCapsule)
                        autoProduceHandler.removeMessages(messageStartMoveStep)
                        autoProduceHandler.removeMessages(messageFinishEncapsulation)
                        autoProduceHandler.removeMessages(messageCornerCut)
                        runOnUiThread {
                            tv_produce_all.isEnabled = false
                            setOperationEnable(false)
                        }
                    }else{
                        isEmergencyStop = false
                        runOnUiThread {
                            tv_produce_all.isEnabled = true
                            setOperationEnable(true)
                        }
                    }
                }
            }
        }
    }

    override fun onDestroy() {
        super.onDestroy()
        SerialPortManager.instance.removeOnSerialPortDataListener(this)
    }

    private fun errorStop(msg:String){
        runOnUiThread {
            setAutoProduceBtnChecked(false)
            setOperationEnable(true)

            MyAlertDialog(msg,object :MyAlertDialog.OnAlertClickListener{
                override fun onRightClick() {

                }
            }).show(supportFragmentManager,null)
        }
    }

    private fun setAutoProduceBtnChecked(isCheck:Boolean){
        tv_produce_all.setOnCheckedChangeListener(null)
        tv_produce_all.isChecked = isCheck
        tv_produce_all.setOnCheckedChangeListener { compoundButton, b ->
            if(b){
                startAllAutoProduce()
            }else{
                stopAllAutoProduce()
            }
        }
    }

}